package com.tarena.csmall.front.web.service;

import cn.tedu.mall.pojo.front.entity.FrontCategoryEntity;
import cn.tedu.mall.pojo.front.vo.FrontCategoryTreeVO;
import com.tarena.csmall.front.web.mapper.CategoryMapper;
import com.tarena.csmall.front.web.repository.CategoryRepository;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 完成数据层的访问
 * 封装控制层需要用到的分类的数据
 */
@Service
public class CategoryService {
    /**
     * 1. 读取当前数据库中所有商品分类
     * 2. 从中取出一级分类 parentId=0 一级分类List
     * 3. 利用一级分类的id 读取二级分类
     * 4. 利用二级分类的id 读取三级分类
     */
    @Autowired
    private CategoryRepository categoryRepository;
    public FrontCategoryTreeVO categoryTree() {
        //1.读取parentId=0的分类 select * from pms_category where parent_id=#{preandId}
        List<FrontCategoryEntity> firstLevelCats = categoryRepository
            .getCategoryChildren(0l);
        //2.循环遍历一级分类,每拿到一个一级分类,利用分类Id查询二级分类
        for (FrontCategoryEntity firstLevelCat : firstLevelCats) {
            //获取一级分类的id
            Long firstLevelCatId = firstLevelCat.getId();
            List<FrontCategoryEntity> secondLevelCats = categoryRepository
                .getCategoryChildren(firstLevelCatId);
            //3.循环遍历二级分类,每拿到一个二级分类,利用分类Id查询三级分类
            for (FrontCategoryEntity secondLevelCat : secondLevelCats) {
                Long secondLevelCatId = secondLevelCat.getId();
                List<FrontCategoryEntity> thirdLevelCats = categoryRepository.getCategoryChildren(secondLevelCatId);
                //4.将三级分类封装到二级分类中
                secondLevelCat.setChildrens(thirdLevelCats);
            }
            //5.将二级分类封装到一级分类中
            firstLevelCat.setChildrens(secondLevelCats);
        }
        //想办法,按照接口要求
        FrontCategoryTreeVO frontCategoryTreeVO = new FrontCategoryTreeVO();
        frontCategoryTreeVO.setCategories(firstLevelCats);
        return frontCategoryTreeVO;
    }
}
